package com.ruoyi.websocket.service;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.websocket.config.SpringWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;

@Service
public class WebSocketService {
    public static final String MODULE_ALARM = "alarm";  //报警模块
    @Autowired
    SpringWebSocketHandler webSocketHandler;
    /**
     * 向指定用户发送websocket消息
     */
    public int sendMessageToUser(String userId,String messageStr){
        TextMessage message = new TextMessage(messageStr);
        webSocketHandler.sendMessageToUser(userId,message);
        System.out.println("向用户["+userId+"]发送消息："+messageStr);
        return 1;
    }
    /**
     * 向多名用户发送websocket消息
     */
    public int sendMessageToUsers(String[] userIds ,String messageStr){
        TextMessage message = new TextMessage(messageStr);
        for(String userId:userIds){
            webSocketHandler.sendMessageToUser(userId,message);
        }
        return 1;
    }
    /**
     * 向多名用户发送websocket消息
     */
    public int sendMessageToAllUsers(String messageStr){
        TextMessage message = new TextMessage(messageStr);
        webSocketHandler.sendMessageToUsers(message);
        return 1;
    }

    public int sendMessageToAllUsers(String moduleName, JSONObject msgBody){
        JSONObject msg = new JSONObject();
        msg.put("moduleName",moduleName);
        msg.put("msgBody",msgBody);
        TextMessage message = new TextMessage(msg.toJSONString());
        webSocketHandler.sendMessageToUsers(message);
        return 1;
    }
}
